package com.nali.dal.mongo.dao;

import java.util.List;
import java.util.Map;

import com.mongodb.DBCollection;
import com.nali.dal.dao.IPreparedQueryDao;
import com.nali.dal.exception.TooManyResultException;
import com.nali.dal.expression.ExpressionValue;
import com.nali.dal.expression.PropertyExpression;
import com.nali.dal.expression.query.Criteria;
import com.nali.dal.mongo.explain.query.Find;
import com.nali.dal.mongo.explain.query.PreparedFind;

public class MongoPreparedQueryDao implements IPreparedQueryDao {
	private DBCollection collection;
	private PreparedFind preparedFind;

	public MongoPreparedQueryDao(DBCollection collection, List<ExpressionValue<Criteria>> crs, List<PropertyExpression<Criteria>> pcs) {
		this.collection = collection;
		Find find = new Find();
		for (PropertyExpression<Criteria> pc : pcs) {
			find.addPropertyCriteria(pc);
		}
		for (ExpressionValue<Criteria> expressionValue : crs) {
			find.addCriteriaValue(expressionValue);
		}
		this.preparedFind = find.prepare();
	}

	@Override
	public List<Map<String, Object>> queryForList(List<Object> params) {
		return preparedFind.find(params, collection, 0, 0);
	}

	@Override
	public Map<String, Object> queryForObject(List<Object> params) {
		List<Map<String, Object>> list = queryForList(params);//TODO 可以在更底层支持
		if(list.size()>1) {
			throw new TooManyResultException(list.size());
		}
		return list.size()==0?null:list.get(0);
	}

	@Override
	public Map<String, Object> queryOne(List<Object> params) {
		List<Map<String, Object>> list = queryForList(params);
		return list.size()==0?null:list.get(0);
	}
}
